import HandleBtn from '@/components/HandleBar/btn';
import type { ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import {
  electricityConsumptionControllerExportDatas as downloadFile,
  electricityConsumptionControllerGetPage as getList,
} from '@/services/ess/statisticElectricityConsumption';
import { downloadFetch } from '@/utils/downloadFile';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useIntl, useModel } from 'umi';
import { TreeNode } from '../help';
import { transformStatisticMultiObjectResponse } from '../helper';
import './Common.less';
const TableList: React.FC<{
  dateType: number;
  deviceInfo: TreeNode;
}> = ({ dateType, deviceInfo }, ref) => {
  const formRef = useRef(null);
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const intl = useIntl();
  const selectedType = useRef(null);
  const treeInfo = useRef<TreeNode>(deviceInfo);
  const [areaFlag, setareaFlag] = useState<boolean>(false);
  const [dataType, setdataType] = useState<string>('1');
  const [columnsState, setColumnsState] = useState({});
  const dateTypeStr = (dateType === 1 && 'day') || (dateType === 2 && 'month') || 'year';
  const [isEmpty, changeIsEmpty] = useState(false);
  const [summary, setSummary] = useState<API.StatisticInfo[]>([]);

  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };

  useEffect(() => {
    if (deviceInfo && deviceInfo.length) {
      selectedType.current = deviceInfo[0]?.nodeType;
      treeInfo.current = setDisabled([deviceInfo[0]]);
      formRef?.current?.submit();
    }
  }, [dateType, deviceInfo]);

  const baseColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      dataIndex: 'date',
      initialValue: dayjs(),
      fieldProps: {
        allowClear: false,
        disabledDate: (current) => {
          return current && current > moment().endOf('day');
        },
      },
      valueType: (dateType === 2 && 'dateMonth') || (dateType === 3 && 'dateYear') || 'date',
      search: {
        transform: (value) => {
          const dateFormat =
            (dateType === 2 && 'YYYY-MM-DD') || (dateType === 3 && 'YYYY-MM-DD') || 'YYYY-MM-DD';
          return {
            date: dayjs(value).format(dateFormat), // 修改
          };
        },
      },
      hideInTable: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'codes',
      valueType: 'treeSelect',
      hideInTable: true,
      initialValue: deviceInfo[0]?.key && [deviceInfo[0]?.key],
      fieldProps: {
        treeData: treeInfo?.current && treeInfo.current?.length ? treeInfo.current : deviceInfo,
        fieldNames: {
          label: 'deviceName',
          value: 'key',
          children: 'subDevices',
        },
        multiple: true,
        maxTagCount: 'responsive',
        showSearch: true,
        treeNodeFilterProp: 'deviceName',
        maxCount: 100,
        onSelect: (...args) => {
          let selectedOptions = args[1];
          if (selectedType.current === null && selectedOptions?.nodeType) {
            selectedType.current = selectedOptions?.nodeType;
            setareaFlag(selectedOptions?.nodeType === 'AREA');
            setdataType(
              selectedOptions?.nodeType === 'ROOT'
                ? '1'
                : selectedOptions?.nodeType === 'AREA'
                ? '3'
                : '2',
            );
          }
          treeInfo.current = setDisabled([deviceInfo[0]]);
        },
        onChange: (...args) => {
          let selectedOptions = args[1];
          if (!selectedOptions.length) {
            //清除后不再做相应限制
            setareaFlag(false);
            setdataType('');
            selectedType.current = null;
            treeInfo.current = setDisabled([deviceInfo[0]]);
          }
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'global.date' }),
      dataIndex: 'date',
      hideInSearch: true,
      width: 130,
      render: (_, record) => {
        if (dateType === 1) {
          return `${record?.startTime}--${record?.endTime}`;
        } else if (dateType === 2) {
          return `${record?.date}`;
        } else if (dateType === 3) {
          return `${record?.date?.slice(0, record?.date.length - 3)}`;
        }
      },
    },
  ];

  const [dynamicColumns, setDynamicColumns] = useState<ProColumns[]>([]);
  const columns = baseColumns.concat(dynamicColumns);

  useImperativeHandle(ref, () => ({
    download: () => {
      const value = formRef?.current?.getFieldsFormatValue() || {};

      downloadFetch(downloadFile, {
        stationId: stationId,
        dateType: dateTypeStr,
        dataType,
        areaFlag,
        ...value,
        ...(dataType === '1' ? { codes: '' } : {}), // 使用三元表达式添加 codes 字段
      });
    },
  }));

  const renderSummary = () => {
    return (
      <ProTable.Summary.Row>
        {columnsState['pageIndex']?.show !== false && (
          <ProTable.Summary.Cell index={0}>
            {intl.formatMessage({ id: 'statistics.analyze.total' })}
          </ProTable.Summary.Cell>
        )}
        {columnsState['date']?.show !== false && (
          <ProTable.Summary.Cell index={2}></ProTable.Summary.Cell>
        )}
        {summary
          .flatMap((item, summaryIndex) => [
            { key: `electricQuantity${summaryIndex + 1}`, value: item.pocConsumptionEnergy },
          ])
          .map(
            (item, index) =>
              columnsState[item.key]?.show !== false && (
                <ProTable.Summary.Cell key={index} index={index + 3}>
                  {item.value}kWh
                </ProTable.Summary.Cell>
              ),
          )}
      </ProTable.Summary.Row>
    );
  };

  return (
    <div>
      <ProTable<
        API.energyGenerationControllerGetPageParams,
        API.ApiResultStatisticElectricityVOStatisticElectricityData
      >
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        formRef={formRef}
        rowKey="reportId"
        request={async (params) => {
          let values = {
            ...params,
            dateType: dateTypeStr,
            dataType,
            areaFlag,
            ...(dataType === '1' ? { codes: '' } : {}), // 使用三元表达式添加 codes 字段
            pageSize: params.pageSize * (params?.codes?.length || 1),
          };

          try {
            const reslut = await getList(values);

            const newPage = transformStatisticMultiObjectResponse(
              { data: reslut?.data?.page },
              params,
              ['electricQuantity'],
            );

            const newRecords = newPage.data?.records;
            if (newRecords.length > 0) {
              setTimeout(() => {
                const newColumns = newRecords[0].devices.flatMap((item, index) => [
                  {
                    title:
                      dataType === '1'
                        ? `${intl.formatMessage({ id: 'statistics.analyze.consumption' })}`
                        : `${item.deviceName ? item.deviceName + '-' : ''}${intl.formatMessage({
                            id: 'statistics.analyze.consumption',
                          })}`,
                    dataIndex: `electricQuantity${index + 1}`,
                    hideInSearch: true,
                    hideInTable: false,
                    width: 156,
                  },
                ]);

                setDynamicColumns(newColumns);
              }, 100);
            }

            changeIsEmpty(Number(newPage.data?.total || 0) === 0);
            const summary = reslut.data?.total?.sort((a, b) =>
              (a.deviceName ?? '').localeCompare(b.deviceName ?? ''),
            );
            console.log('相应的数据', summary);
            setSummary(summary ?? []);

            return newPage;
          } catch (error) {}
        }}
        onReset={() => {
          selectedType.current = deviceInfo[0]?.nodeType;
          treeInfo.current = setDisabled([deviceInfo[0]]);
          formRef?.current?.setFieldsValue({
            codes: [treeInfo.current[0].key],
          });
          formRef?.current?.submit();
        }}
        columns={columns}
        columnsState={{
          value: columnsState,
          onChange: setColumnsState,
        }}
        summary={() => !isEmpty && renderSummary()}
        search={{
          className: 'searchPosInline',
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      />
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  return (
    <>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'statistics.common.export' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(TableList);
export { ToolBarRender };
